package com.explorer.ider.bootguide.fragment;

import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;

import com.explorer.ider.bootguide.MainActivity;
import com.explorer.ider.bootguide.R;
import com.explorer.ider.bootguide.itembean.UserModel;
import com.explorer.ider.bootguide.utils.NetUtil;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

/**
 * Created by Eric on 2016/9/5.
 */
public class FragmentGoogleLogin extends Fragment implements GoogleApiClient.OnConnectionFailedListener{

    private Button justRegisterButton;
    private SignInButton googleRegisterBtn;
    private Button skipTv;
    private int googleButtonWidth,googleButtonHeight;
    private View views;
    private GoogleApiClient mGoogleApiClient;
    private ProgressDialog mProgressDialog;
    private static final int RC_SIGN_IN = 9001;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (views == null){
            views = inflater.inflate(R.layout.fragment_google_login, container,false);
            initViews();
            initData();
        }
        return views;
    }

    private void initData(){

        // Configure sign-in to request the user's ID, email address, and basic
        // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        // [END configure_signin]


        // [START build_client]
        // Build a GoogleApiClient with access to the Google Sign-In API and the
        // options specified by gso.

        try {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .enableAutoManage(getActivity() /* FragmentActivity */, this /* OnConnectionFailedListener */)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // [END build_client]

        // [START customize_button]
        // Customize sign-in button. The sign-in button can be displayed in
        // multiple sizes and color schemes.
        googleRegisterBtn.setSize(SignInButton.SIZE_WIDE);
        googleRegisterBtn.setScopes(gso.getScopeArray());
        // [END customize_button]
        //  signOut();

        if (mGoogleApiClient.isConnected())
        {
            signOut();

        }
    }

    public void initViews() {
        final Animation mAnimationIn , mAnimationOut;
        mAnimationIn = AnimationUtils.loadAnimation(getActivity(), R.anim.view_focus_animation_in);
        mAnimationOut = AnimationUtils.loadAnimation(getActivity(),R.anim.view_focus_animation_out);
        googleRegisterBtn = (SignInButton) views.findViewById(R.id.btn_sign_in);
        googleButtonWidth = googleRegisterBtn.getWidth();
        googleButtonHeight = googleRegisterBtn.getHeight();
        mAnimationIn.setFillAfter(true);
        mAnimationOut.setFillAfter(true);
        skipTv = (Button) views.findViewById(R.id.skipTv);

        googleRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NetUtil.isNetworkAvailable(getActivity())) {
                    //navigate to new screen
                    Toast.makeText(getActivity(), "show google register screens", Toast.LENGTH_SHORT).show();

                    signIn();

                }
            }
        });
        googleRegisterBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Toast.makeText(getActivity(),"111",Toast.LENGTH_SHORT).show();
                if (hasFocus) {
                    performAnimate(v, googleButtonWidth, (int) (googleButtonWidth * 1.2f));
                    performAnimate(v, googleButtonHeight, (int) (googleButtonHeight * 1.2f));
                }else {
                    performAnimate(v,  (int) (googleButtonWidth * 1.2f),googleButtonWidth);
                    performAnimate(v, (int) (googleButtonHeight * 1.2f), googleButtonHeight);
                }
            }
        });

        //finishing this only in case of skip- TBD
        skipTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toNextPager();
            }
        });
        skipTv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    v.startAnimation(mAnimationIn);
                }else {
                    v.startAnimation(mAnimationOut);
                }
            }
        });
    }

    private void performAnimate(final View target, final int start, final int end) {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(1, 100);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            //持有一个IntEvaluator对象，方便下面估值的时候使用
            private IntEvaluator mEvaluator = new IntEvaluator();

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                //获得当前动画的进度值，整型，1-100之间
                int currentValue = (Integer)animator.getAnimatedValue();

                //计算当前进度占整个动画过程的比例，浮点型，0-1之间
                float fraction = currentValue / 100f;

                //这里我偷懒了，不过有现成的干吗不用呢
                //直接调用整型估值器通过比例计算出宽度，然后再设给Button
                target.getLayoutParams().width = mEvaluator.evaluate(fraction, start, end);
                target.requestLayout();
            }
        });

        valueAnimator.setDuration(5000).start();
    }

    private void focusChangeAnimationOut(View v){
        ObjectAnimator.ofInt(v,"Width",500).setDuration(200).start();
        ObjectAnimator.ofInt(v,"Height",500).setDuration(200).start();
    }

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.d("WScreen", "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }

    }

    public FragmentGoogleLogin(){

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
            Toast.makeText(getActivity(), getString(R.string.string_google_login_success), Toast.LENGTH_SHORT).show();
            toNextPager();
        }else{
            Toast.makeText(getActivity(), getString(R.string.string_google_login_failure), Toast.LENGTH_SHORT).show();
        }
    }

    // [START handleSignInResult]在此处可以展示登陆信息
    private void handleSignInResult(GoogleSignInResult result) {
        Log.d("wscreen", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show pre-populated UI.

            GoogleSignInAccount googleSignInAccount = result.getSignInAccount();
            Toast.makeText(getActivity(), "signed in from" + googleSignInAccount.getEmail(), Toast.LENGTH_SHORT).show();

            UserModel.getInstance().setEmail(googleSignInAccount.getEmail(), getActivity());

            if (googleSignInAccount.getPhotoUrl()!=null)
                // UserModel.getInstance().setUserImageUrl(googleSignInAccount.getPhotoUrl().toString());

                if (googleSignInAccount.getDisplayName() != null) {
                    UserModel.getInstance().setUserName(googleSignInAccount.getDisplayName());
                    System.out.println(".....k  "+googleSignInAccount.getDisplayName());

                }
// TODO: send the object to next activity and prefill details in  the form
            toNextPager();
        }
        else
        {
//            Toast.makeText(getActivity(), " ", Toast.LENGTH_SHORT).show();
            // Signed out, show unauthenticated UI.
            //updateUI(false);
        }

    }

    // [END handleSignInResult]

    // [START signIn]
    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    //not needed

    // [START signOut]
    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
                        // updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }


    public void onBackPressed() {
        mProgressDialog.onBackPressed();
    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d("wscreen", "onConnectionFailed:" + connectionResult);

    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage(getString(R.string.string_google_login_loading));
            mProgressDialog.setIndeterminate(true);
        }

//        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void toNextPager(){
        Intent intent = new Intent();
        intent.setAction(MainActivity.ACTION_TO_NEXT_PAGER5);
        getActivity().sendBroadcast(intent);

    }

}
